import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import fs from 'fs'
import path from 'path'

export function GetRouter(app , dirPath = 'Controllers'){
  let router = new Router()
  app.use(bodyParser())
  dirPath = path.join(path.resolve('.'),`./${dirPath}`)
  if(fs.existsSync(dirPath)){
    let newFliePath = fs.readdirSync(dirPath).filter(item => item.endsWith('.js')).map(item =>'file:///' + path.join(dirPath,item))
    newFliePath.forEach(async item => {
      let {obj} = await import(newFliePath)
      obj.forEach(item => {
        if (item.method === 'get') router.get(item.url,item.fn)
        if (item.method === 'post') router.post(item.url,item.fn)
        if (item.method === 'put') router.put(item.url,item.fn)
        if (item.method === 'delete') router.delete(item.url,item.fn)
      })
    })
    return router.routes()
  }else{
    console.log('文件路径错误')
  }

}